package com.naxiang.cn.naxiangstram;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;

import com.baidu.cloud.bdrtmpsession.BDRtmpSessionBasic;
import com.baidu.cloud.gpuimage.ColorAdjustFilter;
import com.baidu.cloud.gpuimage.GPUImageSoftenBeautyFilter;
import com.baidu.cloud.gpuimage.basefilters.GPUImageFilter;
import com.baidubce.BceClientConfiguration;
import com.baidubce.services.bos.model.InitiateMultipartUploadRequest;
import com.baidubce.services.bos.model.InitiateMultipartUploadResponse;
import com.baidubce.services.vod.VodClient;
import com.baidubce.services.vod.model.GenerateMediaIdResponse;
import com.naxiang.cn.config.LiveConfig;
import com.naxiang.cn.config.ProcessConfig;
import com.naxiang.cn.listener.ProcessStateListener;
import com.naxiang.cn.session.LiveCaptureSession;
import com.naxiang.cn.session.MediaProcessSession;
import com.naxiang.cn.utils.BitmapUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
public class OldStream extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_MEDIA_PROJECTION = 100;
    private SurfaceView mSurfaceView;
    private ImageButton mClose;
    private ImageButton mBack;
    private ImageButton mColorConfig;
    private ImageButton mLight;
    private ImageButton mVidoChenged;
    private ImageButton mMusic;
    private ImageButton mLuJing;
    private ImageButton mMoFaBang;
    private ImageButton mCancel;
    private ImageButton mPlay;
    private ImageButton mSure;
    private MediaProjectionManager mMediaProjectionManager = null;


    public int videoHeight     = 1280;
    public int videoWidth      = 720;
    public int captureTimeInMs = 15 * 1000;
    private LiveCaptureSession         mLiveCaptureSession;
    private GPUImageSoftenBeautyFilter beautyFilter;
    private ColorAdjustFilter          colorAdjustFilter;
    private GPUImageFilter             customFilter;

    private AtomicLong tick = new AtomicLong(0);
    private String mp4SavedPath;

    private Disposable captureTask;
    private int mCurrentCamera;
    private boolean mLightOpen = false;
    private MediaProcessSession mMediaProcessSession;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_old_stream);
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        mClose = (ImageButton) findViewById(R.id.imageButton6);

        mBack = (ImageButton) findViewById(R.id.imageButton6);
        mColorConfig = (ImageButton) findViewById(R.id.color_config);
        mLight = (ImageButton) findViewById(R.id.imageButton5);
        mVidoChenged = (ImageButton) findViewById(R.id.imageButton2);
        mMusic = (ImageButton) findViewById(R.id.music);
        mLuJing = (ImageButton) findViewById(R.id.lujing);
        mMoFaBang = (ImageButton) findViewById(R.id.mofabang);
        mCancel = (ImageButton) findViewById(R.id.cancel);
        mPlay = (ImageButton) findViewById(R.id.play);
        mSure = (ImageButton) findViewById(R.id.sure);

        mBack.setOnClickListener(this);
        mColorConfig.setOnClickListener(this);
        mLight.setOnClickListener(this);
        mVidoChenged.setOnClickListener(this);
        mMusic.setOnClickListener(this);
        mLuJing.setOnClickListener(this);
        mMoFaBang.setOnClickListener(this);
        mCancel.setOnClickListener(this);
        mPlay.setOnClickListener(this);
        mSure.setOnClickListener(this);


        //每次打开都要访问权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
        }

        mCurrentCamera = LiveConfig.CAMERA_FACING_BACK;


        Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // 配置录制参数
        LiveConfig.Builder builder = new LiveConfig.Builder();
        builder.setCameraOrientation(90) // 设置相机旋转参数，通常横屏传0度，竖屏传90度
                .setOutputOrientation(0) // 设置产出的视频的逆时针旋转方向，该参数最终用于VideoFilter的setEncodeSize接口
                .setCameraId(LiveConfig.CAMERA_FACING_BACK)  // 设置所使用的相机
                .setVideoWidth(videoWidth)// 设置输出视频的宽（像素个数）
                .setVideoHeight(videoHeight); // 设置输出视频的高（像素个数）


        // 初始化录制Session
        mLiveCaptureSession = new LiveCaptureSession(OldStream.this, builder.build());
        mLiveCaptureSession.setSurfaceHolder(mSurfaceView.getHolder());
        mLiveCaptureSession.setCaptureErrorListener(new LiveCaptureSession.CaptureErrorListener() {
            @Override
            public void onError(int error, String desc) {
                System.out.println("onError: id=" + error + ";info=" + desc);

            }
        });
        // 美颜滤镜
        beautyFilter = new GPUImageSoftenBeautyFilter();
        // 颜色调整滤镜
        colorAdjustFilter = new ColorAdjustFilter(OldStream.this);
        // 其他滤镜：如风格滤镜，自定义滤镜
        customFilter = new GPUImageFilter();

        List<GPUImageFilter> filterList = new ArrayList<>();

        filterList.add(beautyFilter);
        filterList.add(colorAdjustFilter);
        filterList.add(customFilter);
        // 设置美颜、色彩调整、风格等滤镜链
        mLiveCaptureSession.setGPUImageFilters(filterList);

        // 初始化录音与捕获视频的device. 在创建Session时仅调用一次；
        mLiveCaptureSession.setupDevice();

        //重新启动编码器
        mLiveCaptureSession.resume();

    }



    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.imageButton6) {
            //关闭界面的时候释放资源
            mLiveCaptureSession.release();
            mLiveCaptureSession = null;
            finish();
        } else if (viewId == R.id.color_config) {

        //TODO：开启闪光灯
        } else if (viewId == R.id.imageButton5) {
            onClickFlash();

        //TODO:切换摄像头
        } else if (viewId == R.id.imageButton2) {
            onClickSwitch();

            //获取音乐列表，并选择音乐
        } else if (viewId == R.id.music) {
//            onClickBGM();
        } else if (viewId == R.id.lujing) {

        } else if (viewId == R.id.mofabang) {

        //TODO:录制完成取消
        } else if (viewId == R.id.cancel) {
            onClickCancel();
            //TODO:取消的时候删除已经录制的是拼
            delateRido();
        //TODO:开始录制
        } else if (viewId == R.id.play) {
            onClickCapture();
        //TODO:录制完成，确定完成
        } else if (viewId == R.id.sure) {
            onClickFinish();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode != Activity.RESULT_OK) {
                Toast.makeText(this, "User cancelled", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
        } else {
            finish();
        }


        super.onActivityResult(requestCode, resultCode, data);
    }


    //TODO:删除已经录制的视频
    public void delateRido(){
        if (tryStopCapture()) {
            File file = new File(mp4SavedPath);
            if (file.exists()) {
                file.delete();
            }
        }
    }







    /**
     * @return 是否在调用该方法时已经开始拍摄
     */
    private synchronized boolean tryStopCapture() {
        // 如果没有开始拍摄直接返回
        if (tick.get() == 0) {
            return false;
        }
        if (captureTask != null && !captureTask.isDisposed()) {
            captureTask.dispose();
            captureTask = null;
        }
        mLiveCaptureSession.stop();
        mLiveCaptureSession.destroyMp4Muxer();

        return true;
    }

    /**
     * @return 如果由录制状态进入暂停状态则返回 true
     */
    private synchronized boolean tryPauseCapture() {
        if (tick.get() > 0 && captureTask != null && !captureTask.isDisposed()) {
            mLiveCaptureSession.pause();
            captureTask.dispose();
            captureTask = null;
            return true;
        }
        return false;
    }

    //TODO:上传本地视频
    public void upLoadeFile(){



    }
    //TODO:录制完成取消
    public void onClickCancel() {
        tryStopCapture();

    }
    //TODO:录制完成，确定完成
    public void onClickFinish() {
        tryStopCapture();


        //对视频添加效果等
        ProcessConfig.Builder builder = new ProcessConfig.Builder();
        mMediaProcessSession = new MediaProcessSession(OldStream.this, builder.build());

        mMediaProcessSession.setMediaFilePath(mp4SavedPath);

        mp4SavedPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getPath()
                + "/sdk-process-" + System.currentTimeMillis() + ".mp4";

        System.out.println("mp4SavedPath==新生成的"+mp4SavedPath);
        //设置源视频文件路径2
        mMediaProcessSession.configMp4Saver(true, mp4SavedPath);//设置合成视频的存储路径
        mMediaProcessSession.setProcessStateListener(new ProcessStateListener() {
            @Override
            public void onProgress(final int progress) {

            }
            @Override
            public void onFinish(boolean isSuccess, int what) {

                if (isSuccess) {

                    System.out.println("合成成功");
                    //processTint.set("合成成功");
                } else {
                    //processTint.set("合成失败，错误码：" + what);
                    System.out.println("合成失败，错误码：" + what);
                    new File(mp4SavedPath).delete();
                }
            }
        });
        mMediaProcessSession.start();

    }

    //TODO:开始录制
    public void onClickCapture() {

        System.out.println("点击录制了");
        if (!tryPauseCapture()) {
            // 如果还没开始录制
            if (tick.get() == 0) {
                System.out.println("还没开始录制");

                mp4SavedPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
                        .getPath() + "/NaXiang-" + System.currentTimeMillis() + ".mp4";
                // 初始化mp4格式封装器
                mLiveCaptureSession.configMp4Muxer(mp4SavedPath);
                mLiveCaptureSession.start();


            } else {
                System.out.println("已经开始录制了");
                mLiveCaptureSession.resume();
            }

            captureTask = Flowable.interval(10, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .map(new Function<Long, Long>() {
                        @Override
                        public Long apply(@NonNull Long aLong) throws Exception {
                            return tick.getAndIncrement();
                        }
                    })
                    .takeWhile(new Predicate<Long>() {
                        @Override
                        public boolean test(@NonNull Long aLong) throws Exception {

                            return true;
                        }
                    })
                    .doOnComplete(new Action() {
                        @Override
                        public void run() throws Exception {
                            tryPauseCapture();

                        }
                    })
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(@NonNull Long aLong) throws Exception {
                        }
                    });
        }
    }

    //TODO：开启闪光灯
    public void onClickFlash() {
        if (mCurrentCamera == LiveConfig.CAMERA_FACING_FRONT) {
            Toast.makeText(OldStream.this, "使用前置摄像头时不能开启闪光灯", Toast.LENGTH_SHORT).show();
            return;
        }else{
            if (mLightOpen){
                mLiveCaptureSession.toggleFlash(false);
            }else {
                mLiveCaptureSession.toggleFlash(true);
            }
            mLightOpen = !mLightOpen;

        }

        System.out.println("开启闪光灯");
    }

    //TODO:切换摄像头
    public void onClickSwitch() {
        if (mLiveCaptureSession.canSwitchCamera()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (mCurrentCamera == LiveConfig.CAMERA_FACING_BACK) {
                        Log.d("CaptureViewModel", "onClickSwitch: ");
                        mCurrentCamera = LiveConfig.CAMERA_FACING_FRONT;
                        mLiveCaptureSession.switchCamera(mCurrentCamera);
                        if (mLightOpen) {
                            mLiveCaptureSession.toggleFlash(false);
                            mLightOpen = !mLightOpen;
                        }
                    } else {
                        mCurrentCamera = LiveConfig.CAMERA_FACING_BACK;
                        mLiveCaptureSession.switchCamera(mCurrentCamera);
                    }
                }
            }).start();
        } else {
            Toast.makeText(OldStream.this, "抱歉！该分辨率下不支持切换摄像头！", Toast.LENGTH_SHORT).show();
        }
    }

    public void chengeAndUp(){

        new Thread(new Runnable() {
            @Override
            public void run() {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {

                    BitmapUtils.getVoideThumb(mp4SavedPath, 1000);

                } else {
                    //  低于10下执行内容
                    BitmapUtils.getVoidImage(mp4SavedPath);
                }
            }
        }).start();
    }

//    //TODO:BGM
//    public void onClickBGM() {
//        Flowable.fromCallable(new Callable<List<Music>>() {
//            @Override
//            public List<Music> call() throws Exception {
//                return MusicTool.scanMusic(OldStream.this);
//            }
//        })
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<List<Music>>() {
//                    @Override
//                    public void accept(@android.support.annotation.NonNull List<Music> musics) throws Exception {
//
//                    }
//                });
//        }
//    }
    // 设置背景乐
//mLiveCaptureSession.configBackgroundMusic(boolean enableBGM, String bgmPath, boolean isLooping)
//            // 设置背景乐区间，单位为微妙（us）
//            mLiveCaptureSession.configBackgroundMusicClip(long clipStartInUSec, long clipDurationInUSec)
    // 设置录音音量增益，取值[0f, 1f]
//mLiveCaptureSession.setRecordTrackGain(float gain);
//    // 设置背景音音量增益，取值[0f, 1f]
//mLiveCaptureSession.setBGMTrackGain(float gain);

//    // 开启或关闭闪光灯
//mLiveCaptureSession.toggleFlash(boolean flag);
//    // 是否可以切换摄像头
//mLiveCaptureSession.canSwitchCamera();
//    // 切换摄像头
//mLiveCaptureSession.switchCamera(int cameraId);
//    // focus到具体位置
//mLiveCaptureSession.focusToPoint(int x, int y);
//    // 获取最大缩放因子
//mLiveCaptureSession.getMaxZoomFactor();
//    // 设置缩放因子
//mLiveCaptureSession.setZoomFactor(int factor);


}

